<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true"
          >添加角色</el-button
        >
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!-- 条件判断 -->
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <!-- 开 1 关 0 -->
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>
              {{
                row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              size="mini"
              type="textarea"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="btnEditOK(row)"
                >确定</el-button
              >
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定要删除该角色吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="confirmDel(row.id)"
                @cancel="cancelDel"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="text"
                  style="margin-left: 10px"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
          layout="prev, pager, next"
        />
      </el-row>
    </div>
    <el-dialog
      width="500px"
      title="新增角色"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <!-- 表单内容 -->
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            style="width: 300px"
            size="mini"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK"
                >确定</el-button
              >
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, delRole } from '@/api/role'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取列表数据
    async getRoleList() {
      try {
        const { rows, total } = await getRoleList(this.pageParams)
        this.list = rows
        this.pageParams.total = total
        this.initEditState()
      } catch (error) {
        this.$message.error('获取角色列表失败')
      }
    },

    // 初始化编辑状态
    initEditState() {
      this.list.forEach((item) => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },

    // 开始编辑
    btnEditRow(row) {
      row.isEdit = true
      // 复制数据到编辑对象
      Object.assign(row.editRow, {
        name: row.name,
        state: row.state,
        description: row.description
      })
    },

    // 取消编辑
    cancelEdit(row) {
      row.isEdit = false
    },

    // 确认编辑
    async btnEditOK(row) {
      try {
        if (!row.editRow.name || !row.editRow.description) {
          return this.$message.warning('角色和描述不能为空')
        }

        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('更新角色成功')

        // 更新显示数据
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } catch (error) {
        this.$message.error('更新失败')
      }
    },

    // 新增角色
    async btnOK() {
      try {
        await this.$refs.roleForm.validate()
        await addRole(this.roleForm)
        this.$message.success('新增成功')
        this.getRoleList()
        this.btnCancel()
      } catch (error) {
        this.$message.error('新增失败')
      }
    },

    // 取消新增
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },

    // 分页切换
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    async confirmDel(id) {
      try {
        await delRole(id)
        this.$message.success('删除角色成功')

        // 如果当前页是最后一页，且只有一条数据
        if (
          this.list.length === 1 &&
          this.pageParams.page > 1 &&
          this.pageParams.page ===
            Math.ceil(this.pageParams.total / this.pageParams.pagesize)
        ) {
          this.pageParams.page--
        }

        await this.getRoleList()
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败')
      }
    },
    // 取消删除
    cancelDel() {
      this.$message.info('已取消删除')
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
